package router

import (
	"net/http"

	"gitee.com/xiaozefeng/billing-server/handler/bill"
	"gitee.com/xiaozefeng/billing-server/handler/billcategory"
	"gitee.com/xiaozefeng/billing-server/handler/sd"
	"gitee.com/xiaozefeng/billing-server/handler/user"
	"gitee.com/xiaozefeng/billing-server/router/middleware"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
)

func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine {
	g.Use(gin.Recovery())
	g.Use(gin.Logger())
	g.Use(middleware.NoCache)
	g.Use(middleware.Options)
	g.Use(middleware.Secure)

	g.NoRoute(func(c *gin.Context) {
		c.String(http.StatusNotFound, "The incorrect api router.")
	})
	g.Static("/assets", "./assets")

	g.GET("/", middleware.AuthMiddleware(), func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", gin.H{
			"billCategories": billcategory.GetBillCategories(),
		})
	})

	g.POST("/login", user.Login)
	g.GET("/login", func(c *gin.Context) {
		c.HTML(http.StatusOK, "login.html", nil)
	})

	billGroup := g.Group("/v1/bills")
	{
		billGroup.POST("", bill.Create)
		billGroup.PUT("", bill.Update)
		billGroup.GET("/:id,", bill.Get)
		billGroup.DELETE("/:id", bill.Delete)
		billGroup.GET("", bill.List)
	}

	userGroup := g.Group("/v1/users")
	if viper.GetBool("auth") {
		userGroup.Use(middleware.AuthMiddleware())
	}
	{
		userGroup.POST("", user.Create)
		userGroup.PUT("", user.Update)
		userGroup.GET("/:id,", user.Get)
		userGroup.DELETE("/:id", user.Delete)
		userGroup.GET("", user.List)
	}

	billCategoryGroup := g.Group("/v1/bill/categories")
	{
		billCategoryGroup.POST("", billcategory.Create)
		billCategoryGroup.PUT("", billcategory.Update)
		billCategoryGroup.GET("/:id,", billcategory.Get)
		billCategoryGroup.DELETE("/:id", billcategory.Delete)
		billCategoryGroup.GET("", billcategory.List)
	}

	sdGroup := g.Group("/sd")
	{
		sdGroup.GET("/health", sd.HealthCheck)
		sdGroup.GET("/disk", sd.DiskCheck)
		sdGroup.GET("/cpu", sd.CPUCheck)
		sdGroup.GET("/ram", sd.RAMCheck)
	}
	return g
}
